Page({
  data: {
    loading: true,
    members: [],
    selectedMemberId: null,
    recordTypes: ['血压', '血糖', '体重', '体温', '心率'],
    selectedType: '体重',
    timeRanges: ['最近7天', '最近30天', '最近3个月', '最近6个月', '最近1年'],
    selectedTimeRange: '最近30天',
    chartData: {
      categories: [],
      series: []
    },
    canvasWidth: 320,
    canvasHeight: 200,
    avgValue: 0,
    maxValue: 0,
    minValue: 0
  },

  onLoad: function (options) {
    // 获取屏幕宽度，设置图表宽度
    const systemInfo = wx.getSystemInfoSync();
    const screenWidth = systemInfo.windowWidth;
    
    this.setData({
      canvasWidth: screenWidth - 20, // 两侧各留出10rpx的边距
      canvasHeight: 240 // 增加高度以确保有足够空间显示
    });
    
    // 如果传入了成员ID和记录类型，则预选
    if (options.memberId) {
      this.setData({
        selectedMemberId: parseInt(options.memberId)
      });
    }
    
    if (options.type) {
      this.setData({
        selectedType: options.type
      });
    }
    
    this.loadMembers();
  },
  
  onShow: function () {
    // 页面显示时加载数据
    if (this.data.selectedMemberId) {
      this.loadTrendData();
    }
  },
  
  loadMembers: function () {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 从服务器获取家庭成员数据
    wx.request({
      url: 'http://localhost:3000/api/members',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.success) {
          const members = res.data.data.members || [];
          
          this.setData({
            members: members,
            loading: false
          });
          
          // 如果没有预选成员，默认选择第一个
          if (!this.data.selectedMemberId && members.length > 0) {
            this.setData({
              selectedMemberId: members[0].id
            });
            this.loadTrendData();
          } else if (this.data.selectedMemberId) {
            // 如果已有预选成员，加载趋势数据
            this.loadTrendData();
          }
        } else {
          console.error('获取家庭成员失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '获取成员数据失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },
  
  loadTrendData: function () {
    const { selectedMemberId, selectedType, selectedTimeRange } = this.data;
    
    if (!selectedMemberId || !selectedType) {
      return;
    }
    
    this.setData({ loading: true });
    
    // 根据时间范围确定API参数
    let timeRange = '30days';
    switch (selectedTimeRange) {
      case '最近7天':
        timeRange = '7days';
        break;
      case '最近30天':
        timeRange = '30days';
        break;
      case '最近3个月':
        timeRange = '3months';
        break;
      case '最近6个月':
        timeRange = '6months';
        break;
      case '最近1年':
        timeRange = '1year';
        break;
    }
    
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 从服务器获取趋势数据
    wx.request({
      url: 'http://localhost:3000/api/trends',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      data: {
        memberId: selectedMemberId,
        type: selectedType,
        timeRange: timeRange
      },
      success: (res) => {
        if (res.data.success && res.data.data) {
          const trendData = res.data.data;
          
          // 计算统计值
          let avgValue = 0;
          let maxValue = Number.MIN_SAFE_INTEGER;
          let minValue = Number.MAX_SAFE_INTEGER;
          
          const values = trendData.series[0].data;
          if (values && values.length > 0) {
            // 计算平均值
            let sum = 0;
            for (let i = 0; i < values.length; i++) {
              const val = parseFloat(values[i]);
              sum += val;
              
              // 更新最大值和最小值
              if (val > maxValue) maxValue = val;
              if (val < minValue) minValue = val;
            }
            avgValue = (sum / values.length).toFixed(1);
            maxValue = maxValue.toFixed(1);
            minValue = minValue.toFixed(1);
          } else {
            // 没有数据时设置默认值
            avgValue = 0;
            maxValue = 0;
            minValue = 0;
          }
          
          // 设置图表数据
          this.setData({
            loading: false,
            'chartData.categories': trendData.categories || [],
            'chartData.series': [{
              name: selectedType,
              data: values || [],
              format: (val) => {
                switch (selectedType) {
                  case '血压':
                    return val + ' mmHg';
                  case '血糖':
                    return val + ' mmol/L';
                  case '体重':
                    return val + ' kg';
                  case '体温':
                    return val + ' °C';
                  case '心率':
                    return val + ' bpm';
                  default:
                    return val;
                }
              }
            }],
            avgValue: avgValue,
            maxValue: maxValue,
            minValue: minValue
          });
          
          // 渲染图表
          if (values && values.length > 0) {
            this.renderChart();
          }
        } else {
          console.error('获取趋势数据失败:', res.data.message);
          wx.showToast({
            title: res.data.message || '获取趋势数据失败',
            icon: 'none'
          });
          
          // 清空图表数据
          this.setData({
            loading: false,
            'chartData.categories': [],
            'chartData.series': [{
              name: selectedType,
              data: []
            }],
            avgValue: 0,
            maxValue: 0,
            minValue: 0
          });
        }
      },
      fail: (err) => {
        console.error('请求失败:', err);
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },
  
  onMemberChange: function (e) {
    const memberId = parseInt(e.currentTarget.dataset.id);
    
    this.setData({
      selectedMemberId: memberId
    });
    
    this.loadTrendData();
  },
  
  onTypeChange: function (e) {
    const type = e.currentTarget.dataset.type;
    
    this.setData({
      selectedType: type
    });
    
    this.loadTrendData();
  },
  
  onTimeRangeChange: function (e) {
    const timeRange = e.currentTarget.dataset.range;
    
    this.setData({
      selectedTimeRange: timeRange
    });
    
    this.loadTrendData();
  },
  
  renderChart: function () {
    const { chartData, canvasWidth, canvasHeight } = this.data;
    
    if (!chartData.categories.length || !chartData.series.length || !chartData.series[0].data.length) {
      console.log('没有足够的数据来渲染图表');
      return;
    }
    
    try {
      const ctx = wx.createCanvasContext('trendChart');
      
      // 图表边距 - 增加左右和底部边距，避免标签重叠
      const padding = {
        top: 30,
        right: 30,
        bottom: 50,
        left: 70
      };
      
      // 图表区域尺寸
      const chartWidth = canvasWidth - padding.left - padding.right;
      const chartHeight = canvasHeight - padding.top - padding.bottom;
      
      // 获取数据值范围
      let minValue = Number.MAX_SAFE_INTEGER;
      let maxValue = Number.MIN_SAFE_INTEGER;
      
      const data = chartData.series[0].data;
      for (let i = 0; i < data.length; i++) {
        const val = parseFloat(data[i]);
        if (val < minValue) minValue = val;
        if (val > maxValue) maxValue = val;
      }
      
      // 为了更好的视觉效果，扩大值范围
      const valueRange = maxValue - minValue;
      minValue = Math.max(0, minValue - valueRange * 0.1);
      maxValue = maxValue + valueRange * 0.1;
      
      // 绘制坐标轴
      ctx.beginPath();
      ctx.setLineWidth(1);
      ctx.setStrokeStyle('#cccccc');
      
      // X轴
      ctx.moveTo(padding.left, canvasHeight - padding.bottom);
      ctx.lineTo(canvasWidth - padding.right, canvasHeight - padding.bottom);
      
      // Y轴
      ctx.moveTo(padding.left, padding.top);
      ctx.lineTo(padding.left, canvasHeight - padding.bottom);
      
      ctx.stroke();
      
      // 绘制网格线和Y轴标签
      const yTickCount = 5;
      const yStep = chartHeight / (yTickCount - 1);
      const valueStep = (maxValue - minValue) / (yTickCount - 1);
      
      ctx.setFontSize(12);
      ctx.setFillStyle('#666666');
      ctx.setTextAlign('right');
      
      for (let i = 0; i < yTickCount; i++) {
        const y = canvasHeight - padding.bottom - i * yStep;
        const value = minValue + i * valueStep;
        
        // 网格线
        ctx.beginPath();
        ctx.setLineWidth(0.5);
        ctx.setStrokeStyle('#eeeeee');
        ctx.moveTo(padding.left, y);
        ctx.lineTo(canvasWidth - padding.right, y);
        ctx.stroke();
        
        // Y轴标签 - 增加距离
        ctx.fillText(value.toFixed(1), padding.left - 10, y + 4);
      }
      
      // 绘制X轴标签
      const xTickCount = Math.min(7, chartData.categories.length);
      const xStep = chartWidth / (chartData.categories.length - 1);
      const xLabelStep = Math.ceil(chartData.categories.length / xTickCount);
      
      ctx.setTextAlign('center');
      
      for (let i = 0; i < chartData.categories.length; i += xLabelStep) {
        const x = padding.left + i * xStep;
        const label = chartData.categories[i];
        
        // X轴标签
        ctx.fillText(label, x, canvasHeight - padding.bottom + 20);
      }
      
      // 绘制数据线
      if (data.length > 1) {
        ctx.beginPath();
        ctx.setLineWidth(2);
        ctx.setStrokeStyle('#4CAF50');
        
        for (let i = 0; i < data.length; i++) {
          const x = padding.left + i * xStep;
          const value = parseFloat(data[i]);
          const y = canvasHeight - padding.bottom - ((value - minValue) / (maxValue - minValue)) * chartHeight;
          
          if (i === 0) {
            ctx.moveTo(x, y);
          } else {
            ctx.lineTo(x, y);
          }
        }
        
        ctx.stroke();
      }
      
      // 绘制数据点
      for (let i = 0; i < data.length; i++) {
        const x = padding.left + i * xStep;
        const value = parseFloat(data[i]);
        const y = canvasHeight - padding.bottom - ((value - minValue) / (maxValue - minValue)) * chartHeight;
        
        ctx.beginPath();
        ctx.setFillStyle('#4CAF50');
        ctx.arc(x, y, 3, 0, 2 * Math.PI);
        ctx.fill();
        
        ctx.beginPath();
        ctx.setFillStyle('#ffffff');
        ctx.arc(x, y, 1.5, 0, 2 * Math.PI);
        ctx.fill();
      }
      
      // 绘制图表标题
      ctx.setFontSize(14);
      ctx.setFillStyle('#333333');
      ctx.setTextAlign('center');
      ctx.fillText(this.data.selectedType + '趋势图', canvasWidth / 2, 20);
      
      ctx.draw();
    } catch (error) {
      console.error('渲染图表错误:', error);
      wx.showToast({
        title: '图表渲染失败',
        icon: 'none'
      });
    }
  }
}) 